import { computed, ref, readonly } from 'vue'
import store from '@/store'
import Contact from '@/api/client/contact.js'
const contact = {}
contact.loaded = ref(false)
contact.raw = ref({})
contact.transformed = ref({})
export function useContactInfo(id, resolve = () => {}, noCache = false) {
  if (!contact.loaded.value || noCache) {
    getData(id, resolve)
  } else {
    resolve({
      raw: readonly(contact.raw),
      transformed: readonly(contact.transformed)
    })
  }
  const reload = getData.bind(this, id, resolve)
  return {
    contact: {
      raw: readonly(contact.raw),
      transformed: readonly(contact.transformed)
    },
    reload
  }
}
function getData(id, resolve) {
  Contact.detail(id).then(async res => {
    contact.raw.value = res.data
    const dict = ref(computed(() => store.state.dict))
    await store.dispatch('dict/getClientTypes')
    await store.dispatch('dict/getContactTypes')
    await store.dispatch('dict/getIMTypes')
    contact.loaded.value = true
    resolve({
      raw: readonly(contact.raw),
      transformed: readonly(contact.transformed)
    })
    const gender = dict.value.genders.find(gender => gender.value === contact.raw.value.gender)
    contact.transformed.value.gender = gender ? gender.text : contact.raw.value.gender
    const contactType = dict.value.contactTypes.find(type => type.value === contact.raw.value.contactType)
    contact.transformed.value.contactType = contactType ? contactType.text : contact.raw.value.contactType
    const IM = dict.value.IMTypes.find(im => im.value === contact.raw.value.im)
    contact.transformed.value.im = IM ? IM.text : contact.raw.value.im
  })
}
